package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.TouristDao;
import model.Tourist;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Register() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at: ").append(request.getContextPath());
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		String phone = request.getParameter("phone");
		System.out.println(phone);
//		String p1 = phone.substring(0,6);
//		String p2 = phone.substring(6,10);
//		int ph1 = Integer.parseInt(p1);
//		int ph2 = Integer.parseInt(p2);
//		int phInt = ph1*100000+ph2;
//		System.out.println(phInt);
//		
		Tourist tourist = new Tourist();
		tourist.setAge(Integer.parseInt(age));
		tourist.setEmail(email);
		tourist.setName(name);
		tourist.setPassword(password);
		tourist.setTelphone(phone);
		try {
			Tourist touristfind = TouristDao.getTouristNoCache(email);
			if (null == touristfind) {
				TouristDao.addTourist(tourist);
				out.print("<script>alert('注册成功，请登录');window.location.href='Login.html'</script>");
				
			} else {
				out.print("<script>alert('该账户已存在');window.location.href='Register.html'</script>");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
